import { Content } from "./Content";
import { Binary, ImageContent, ImageFormat, MimeType } from "easy-template-x";
import * as echarts from 'echarts';
import { ECBasicOption } from "echarts/types/dist/shared";
import { Resvg } from '@resvg/resvg-js';

export class Echart extends Content implements ImageContent {
    _type: "image";
    width: number;
    height: number;
    source: Binary;
    altText?: string;
    format: ImageFormat;
    constructor(width: number, height: number) {
        super('image');
        this.width = width;
        this.height = height;
        this.format = MimeType.Png;
    }
    setOptions(options: ECBasicOption) {
        const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: this.width, height: this.height });
        chart.setOption({backgroundColor: '#fff', ...options});
        const svgStr = chart.renderToSVGString();
        var self = this;
        const resvg = new Resvg(svgStr, {});
        const pngData = resvg.render();
        const pngBuffer = pngData.asPng();
        self.source = pngBuffer;
        chart.dispose();
        // this.source = Buffer.from(svgStr, 'utf-8');
        // chart.dispose();
    }
}